package cn.maihe.elg.operation.utils;

import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.model.enums.GuaranteeTemplateType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 自动匹配模板工具类
 * @author SSX
 * @Date 2025/07/08
 */
@Component
@Slf4j
public class AutoDiscernTemplateUtil {
    private static AutoDiscernTemplateUtil autoDiscernTemplateUtil;

    @Value("${cn.maihe.elg.operation.template.auto-discern:false}")
    private Boolean autoDiscern;

    @Value("${cn.maihe.elg.operation.template.tender-project-type-relation:null}")
    private String tenderProjectTypeRelation;

    @Value("${cn.maihe.elg.operation.template.exchange-centers:null}")
    private String [] exchangeCenters;

    @PostConstruct
    public void init() {
        autoDiscernTemplateUtil = this;
        autoDiscernTemplateUtil.autoDiscern = this.autoDiscern;
        autoDiscernTemplateUtil.tenderProjectTypeRelation = this.tenderProjectTypeRelation;
        autoDiscernTemplateUtil.exchangeCenters = this.exchangeCenters;
    }

    public static Long getTemplateIdByTenderProjectType(CenterNoEnum centerNoEnum,String tenderProjectType){
        ElgLogger.info(log, log -> log.info("centerNoEnum:{};tenderProjectType:{}", centerNoEnum,tenderProjectType));
        if(!autoDiscernTemplateUtil.autoDiscern){
            return null;
        }

        if(Objects.isNull(autoDiscernTemplateUtil.exchangeCenters)){
            return null;
        }

        List<String> exchangeCenterList = Arrays.asList(autoDiscernTemplateUtil.exchangeCenters);
        if(Objects.isNull(centerNoEnum)){
            return null;
        }

        if(!exchangeCenterList.contains(centerNoEnum.getCenterNo())){
            return null;
        }

        if(StringUtils.isBlank(autoDiscernTemplateUtil.tenderProjectTypeRelation)){
            return null;
        }

        if(StringUtils.isBlank(tenderProjectType)){
            return GuaranteeTemplateType.defaultTemp.getTemplateId();
        }

        String[] tenderProjectTypeRelations = autoDiscernTemplateUtil.tenderProjectTypeRelation.split(";");
        Optional<String> tenderProjectTypeRelation = Arrays.stream(tenderProjectTypeRelations).filter(item -> item.split("&")[0].equals(tenderProjectType)).findFirst();
        return tenderProjectTypeRelation.map(s -> new Long(s.split("&")[1])).orElseGet(GuaranteeTemplateType.defaultTemp::getTemplateId);
    }
}
